package com.zdsoft.blp.zongbuju.shouye.linliquan.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.zdsoft.blp.R;
import com.zdsoft.blp.gongyong.API.API;
import com.zdsoft.blp.gongyong.camera.Camera;
import com.zdsoft.blp.gongyong.fanhui.FanHuiView;
import com.zdsoft.blp.gongyong.net.BaseActivity;
import com.zdsoft.blp.gongyong.net.Net;
import com.zdsoft.blp.gongyong.net.NetCallback;
import com.zdsoft.blp.gongyong.upLoad.Base64ToString;
import com.zdsoft.blp.zongbuju.shouye.linliquan.adapter.FBgvAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/3.
 */
public class FBESActivity extends BaseActivity implements NetCallback{
    private FanHuiView fh_title;
    private TextView tv_zr,send;
    private EditText title,lianxiren,dianhua,miaoshu,et_zr;
    private GridView gv;
    private Spinner sp;
    private String XZLX = null, id = null,bt ;
    private ImageView iv_xiangji;
    private List<Bitmap> list;
    private FBgvAdapter adapter;
    @Override
    protected void init() {
        setContentView(R.layout.linli_zhuanrang_fb);
        send = find(R.id.send);
        title = find(R.id.title);
        lianxiren = find(R.id.lianxiren);
        dianhua = find(R.id.dianhua);
        miaoshu = find(R.id.miaoshu);
        fh_title = find(R.id.fh_title);
        tv_zr  = find(R.id.tv_zr);
        et_zr = find(R.id.et_zr);
        sp = find(R.id.sp);
        gv=find(R.id.gv);
        iv_xiangji=find(R.id.iv_xiangji);
        Intent intent = getIntent();
        bt = intent.getStringExtra("title");
        fh_title.getTv_title().setText(bt);
        if(bt.equals("转让")){
            tv_zr.setText("转让价（￥）");
            tv_zr.setTextSize(18);
            et_zr.setHint("输入转让价（选填）");
        }else{
            tv_zr.setText("求购价（￥）");
            tv_zr.setTextSize(18);
            et_zr.setHint("输入求购价（选填）");
        }
        list=new ArrayList<>();
        adapter = new FBgvAdapter(list, getApplicationContext());
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list.size()==position){
                    Camera.setOnClickListener(iv_xiangji, FBESActivity.this);
                }
            }
        });
        final String[] mItems = getResources().getStringArray(R.array.fenlei);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mItems);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        sp.setAdapter(adapter);
        sp.setPrompt("请选择分类");
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                XZLX = mItems[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("转让".equals(bt)){
                    getNet(1);
                }else {
                    getNet(2);
                }
            }
        });
    }

    private void getNet(int i) {
        //用户id；
        SharedPreferences sp = getSharedPreferences("info", Context.MODE_PRIVATE);
        String uerrId = sp.getString("userId","");
        //小区id
        sp =FBESActivity.this.getSharedPreferences("info", Context.MODE_PRIVATE);
        String code = sp.getString("communityCode", "");
        Net net=new Net();
        net.url= API.ESINFO_URL;
        net.nameSpace=API.ESINFO_NAMESPACE;
        String getTitle=title.getText().toString().trim();
        String getMiaoshu=miaoshu.getText().toString().trim();
        String getLianxiren=lianxiren.getText().toString().trim();
        String getDianhua=dianhua.getText().toString().trim();
        String getJiage=et_zr.getText().toString().trim();
        if (getTitle!=null&&getMiaoshu!=null&&getLianxiren!=null&&getDianhua!=null&&getJiage!=null){
            switch (i){
                case 1:
                    net.methodName=API.ESINFOSAVEBYSELL;//esInfoSaveBySell
                    Map<String,Object>map=new HashMap<>();
                    map.put("id","");
                    map.put("comIds",code);
                    map.put("title",getTitle);
                    map.put("content",getMiaoshu);
                    map.put("contact",getLianxiren);
                    map.put("contactPhone",getDianhua);
                    map.put("price",getJiage);
                    map.put("tempFileIds",getImageStr());
                    map.put("userId",uerrId);
                    map.put("oldPrice","");
                    map.put("oldNew","");
                    map.put("exchange","");
                    map.put("type",XZLX);
                    net.parms=map;
                    break;
                case 2:
                    net.methodName=API.ESINFOSAVEBYBUY;//esInfoSaveByBuy
                    Map<String,Object>map1=new HashMap<>();
                    map1.put("id","");
                    map1.put("comIds",code);
                    map1.put("title",getTitle);
                    map1.put("content",getMiaoshu);
                    map1.put("contact",getLianxiren);
                    map1.put("contactPhone",getDianhua);
                    map1.put("price",getJiage);
                    map1.put("tempFileIds",getImageStr());
                    map1.put("userId",uerrId);
                    map1.put("oldNew","");
                    map1.put("type","");
                    net.parms=map1;
                    break;
            }
            getServer(net,this);
        }else {
            Toast.makeText(FBESActivity.this,"请完整填写信息",Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Camera.dialog.dismiss();
        switch (requestCode) {
            case Camera.PAI:
                if (resultCode != RESULT_CANCELED) {
                    try {
                        FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory() + "/image.jpg");
                        Bitmap bitmap = BitmapFactory.decodeStream(in);
                        list.add(bitmap);
                        adapter.notifyDataSetChanged();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case Camera.XUAN:
                if (resultCode != RESULT_CANCELED) {
                    ContentResolver resolver = getContentResolver();
                    InputStream in = null;
                    try {
                        in = resolver.openInputStream(data.getData());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    list.add(bitmap);
                    adapter.notifyDataSetChanged();
                }
                break;
        }
    }
    private String getImageStr(){
        String strImg = "";
        for(int i = 0;i<list.size();i++){
            strImg+= Base64ToString.toString(list.get(i));
            //strImg+=";";
        }
        return  strImg;
    }

    @Override
    public void onResponse(boolean flag, int code, String res) {
        try {
            JSONObject object=new JSONObject(res);
            Toast.makeText(FBESActivity.this,object.getString("msg"),Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


}
